﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
using BigTestV3.common;
using BigTestV3.xmlHelp;

namespace BigTestV3
{
    public partial class frmLogin : Form
    {
        public frmLogin()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 登录事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SubmitClick(object sender, EventArgs e)
        {
            string user = txtUser.Text.Trim();
            string pwd = txtPwd.Text.Trim().ToLower();
            XmlTestPlaceStu student;

            //选择学生
            if (rabStu.Checked)
            {
                if (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(pwd))
                {
                    msgDiv.MsgDivShow("用户名或密码为空");
                }
                else
                {
                    if (Validate(user, pwd, out student))
                    {
                        msgDiv.MsgDivShow("登录成功");

                        CurrStu curr = student == null ? null : new CurrStu
                                                 {
                                                     Number = user,
                                                     Name = student.Name,
                                                     StudentId = student.StudentID == null ? 0 : (long)student.StudentID,
                                                 };
                        string path = FilePathTotal.CurrStuPath;
                        XmlHelper.XmlSerializeToFile(curr, path, Encoding.UTF8);

                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        msgDiv.MsgDivShow("用户名或密码错误");
                    }
                }
            }
            //选择教师
            else if (rabTec.Checked)
            {
                if (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(pwd))
                {
                    msgDiv.MsgDivShow("用户名或者密码不能为空");
                }
                else
                {
                    try
                    {
                        string strpwd = Md5Helper.ToMd5(pwd);
                        string str = GetUrltoHtml(FilePathTotal.LoginUrl 
                            + "PapersHtml/PapersHtmlHandel/PapersHtmlInfoHandler.ashx?workID=" 
                            + user + "&password=" + strpwd);
                        XmlHelper.StringToXml(str, FilePathTotal.DownloadInfoPath);
                        if (str != "")
                        {
                            msgDiv.MsgDivShow("登陆成功");
                            this.DialogResult = DialogResult.Yes;
                            this.Close();
                        }
                        else
                        {
                            msgDiv.MsgDivShow("用户名或密码错误");
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
        }

        /// <summary>
        /// 验证学生是否是本考场的
        /// </summary>
        /// <param name="stuNum"></param>
        /// <param name="stuPwd"></param>
        /// <returns></returns>
        private bool Validate(string stuNum, string stuPwd, out XmlTestPlaceStu student)
        {
            List<XmlTestPlaceStu> students = GetStudentList();
            if (students != null)
            {
                foreach (XmlTestPlaceStu item in students)
                {
                    if (string.Equals(item.StudentNumber, stuNum) 
                        && string.Equals(item.Password.ToUpper(), Md5Helper.ToMd5(stuPwd)))
                    {
                        student = item;
                        return true;
                    }
                }
            }

            student = null;
            return false;
        }


        /// <summary>
        /// 获取本考场的学生集合
        /// </summary>
        /// <returns></returns>
        private List<XmlTestPlaceStu> GetStudentList()
        {
            string path = FilePathTotal.TestInfoPath;
            List<XmlTestPlaceStu> student = null;
            BigTestInfo papers = null;
            
            if (File.Exists(path))
            {
                papers = XmlHelper.XmlDeserializeFromFile<BigTestInfo>(path, Encoding.UTF8);
            }
            else
            {
                msgDiv.MsgDivShow("请下载考试相关的信息");
            }

            if (papers != null)
            {
                student = papers.TestTestPlaceStu;
            }
            GetAnswerAndDeserialize();
            return student;
        }

        /// <summary>
        /// 设置事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SetClick(object sender, EventArgs e)
        {
            frmStuSet stuSet = new frmStuSet();
            stuSet.ShowDialog();
        }

        /// <summary>
        /// 窗体初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoginLoad(object sender, EventArgs e)
        {
            this.MaximizeBox = false;
            skinEngine1.SkinFile = FilePathTotal.SkinPath;
        }

        /// <summary>
        /// 根据url获取xml
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetUrltoHtml(string url)
        {
            try
            {
                WebRequest wReq = WebRequest.Create(url);
                WebResponse wResp = wReq.GetResponse();
                Stream respStream = wResp.GetResponseStream();
                using (StreamReader reader = new StreamReader(respStream, Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return "";
            }
        }

        private void GetAnswerAndDeserialize()
        {
            string path = FilePathTotal.TestInfoPath;
            List<XmlPapersDetail> details = null;
            XmlPaper paper = null;
            XmlAnswer answers = null;
            XmlTest test = null;
            BigTestInfo papers = null;
            
            if (File.Exists(path))
            {
                papers = XmlHelper.XmlDeserializeFromFile<BigTestInfo>(path, Encoding.UTF8);
            }
            
            if (papers != null)
            {
                paper = papers.TestPaper;
                details = papers.TestPapersDetail;
                test = papers.TestTest;
            }
            
            if (details != null)
            {
                List<AnswerDetail> ans = new List<AnswerDetail>();

                foreach (XmlPapersDetail detail in details)
                {
                    AnswerDetail answerDetail = new AnswerDetail()
                                                    {
                                                        Answer = detail.Answers,
                                                        TestLibraryId = detail.TestLibraryID ?? 0,
                                                        TotalScore = detail.TotalScore ?? 0,
                                                        AnswerStyle = detail.AnswerStyle,
                                                    };
                    ans.Add(answerDetail);
                }
                answers = new XmlAnswer() { TestId = test.TestID, Answers = ans, TestTime = paper.TestTime ?? 0 };
                XmlHelper.XmlSerializeToFile(answers, FilePathTotal.AnswerCheckPath, Encoding.UTF8);
            }
        }

    }
}
